<template>
  <el-dialog
    v-model="visible"
    title="用户关系管理"
    width="800px"
    :before-close="handleClose"
  >
    <div v-loading="loading" class="relations-management">
      <!-- 关系统计 -->
      <el-row :gutter="20" class="stats-section">
        <el-col :span="8">
          <div class="stat-card friends">
            <div class="stat-number">{{ relations.friends.length }}</div>
            <div class="stat-label">好友</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="stat-card blacklist">
            <div class="stat-number">{{ relations.blacklist.length }}</div>
            <div class="stat-label">黑名单</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="stat-card total">
            <div class="stat-number">{{ relations.friends.length + relations.blacklist.length }}</div>
            <div class="stat-label">关系总数</div>
          </div>
        </el-col>
      </el-row>

      <!-- 关系列表 -->
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="好友列表" name="friends">
          <div class="tab-content">
            <div class="tab-header">
              <span>好友列表 ({{ relations.friends.length }} 个)</span>
              <el-button type="primary" size="small" @click="handleAddFriend">
                <el-icon><user-filled /></el-icon>
                添加好友
              </el-button>
            </div>
            
            <div v-if="relations.friends.length > 0" class="relations-list">
              <div
                v-for="relation in relations.friends"
                :key="relation.id"
                class="relation-item"
              >
                <el-avatar :src="getFullImageUrl(relation.target.avatar_url)" :size="50">
                  <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
                </el-avatar>
                
                <div class="relation-info">
                  <div class="relation-name">{{ relation.target.nickname }}</div>
                  <div class="relation-details">
                    <span class="relation-id">ID: {{ relation.target.id }}</span>
                    <span class="relation-phone">{{ relation.target.phone || '未绑定手机' }}</span>
                  </div>
                  <div class="relation-time">
                    添加时间: {{ formatDate(relation.created_at) }}
                  </div>
                </div>
                
                <div class="relation-actions">
                  <el-button type="warning" size="small" @click="handleMoveToBlacklist(relation)">
                    移至黑名单
                  </el-button>
                  <el-button type="danger" size="small" @click="handleDeleteRelation(relation)">
                    删除关系
                  </el-button>
                </div>
              </div>
            </div>
            <el-empty v-else description="暂无好友" :image-size="80" />
          </div>
        </el-tab-pane>

        <el-tab-pane label="黑名单" name="blacklist">
          <div class="tab-content">
            <div class="tab-header">
              <span>黑名单 ({{ relations.blacklist.length }} 个)</span>
              <el-button type="warning" size="small" @click="handleAddBlacklist">
                <el-icon><warning /></el-icon>
                添加黑名单
              </el-button>
            </div>
            
            <div v-if="relations.blacklist.length > 0" class="relations-list">
              <div
                v-for="relation in relations.blacklist"
                :key="relation.id"
                class="relation-item blacklist-item"
              >
                <el-avatar :src="getFullImageUrl(relation.target.avatar_url)" :size="50">
                  <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
                </el-avatar>
                
                <div class="relation-info">
                  <div class="relation-name">{{ relation.target.nickname }}</div>
                  <div class="relation-details">
                    <span class="relation-id">ID: {{ relation.target.id }}</span>
                    <span class="relation-phone">{{ relation.target.phone || '未绑定手机' }}</span>
                  </div>
                  <div class="relation-time">
                    拉黑时间: {{ formatDate(relation.created_at) }}
                  </div>
                </div>
                
                <div class="relation-actions">
                  <el-button type="success" size="small" @click="handleMoveToFriends(relation)">
                    移至好友
                  </el-button>
                  <el-button type="danger" size="small" @click="handleDeleteRelation(relation)">
                    删除关系
                  </el-button>
                </div>
              </div>
            </div>
            <el-empty v-else description="黑名单为空" :image-size="80" />
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="fetchRelations">刷新数据</el-button>
      </span>
    </template>

    <!-- 添加关系对话框 -->
    <AddRelationDialog
      v-model="addDialogVisible"
      :user-id="user?.id"
      :relation-type="addRelationType"
      @added="fetchRelations"
    />
  </el-dialog>
</template>

<script>
import { ref, reactive, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserDetail, getUserRelations, createUserRelation, updateUserRelation, deleteUserRelation } from '@/api/user'
import AddRelationDialog from './AddRelationDialog.vue'

export default {
  name: 'UserRelationsDialog',
  components: {
    AddRelationDialog
  },
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    user: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['update:modelValue', 'updated'],
  setup(props, { emit }) {
    const visible = ref(props.modelValue)
    const loading = ref(false)
    const activeTab = ref('friends')
    const addDialogVisible = ref(false)
    const addRelationType = ref('friend')

    const relations = reactive({
      friends: [],
      blacklist: []
    })

    const imageBaseUrl = ref(process.env.VUE_APP_IMAGE_BASE_URL || 'https://hm.yunxitech.cn')

    // 监听对话框显示状态
    watch(() => props.modelValue, (val) => {
      visible.value = val
      if (val && props.user?.id) {
        fetchRelations()
      }
    })

    watch(visible, (val) => {
      emit('update:modelValue', val)
    })

    // 获取用户关系
    const fetchRelations = async () => {
      loading.value = true
      try {
        const response = await getUserDetail(props.user.id)
        relations.friends = response.data.relations.friends || []
        relations.blacklist = response.data.relations.blacklist || []
      } catch (error) {
        ElMessage.error('获取用户关系失败：' + error.message)
      } finally {
        loading.value = false
      }
    }

    // 格式化日期
    const formatDate = (dateString) => {
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    }

    // 切换标签页
    const handleTabChange = (tabName) => {
      activeTab.value = tabName
    }

    // 添加好友
    const handleAddFriend = () => {
      addRelationType.value = 'friend'
      addDialogVisible.value = true
    }

    // 添加黑名单
    const handleAddBlacklist = () => {
      addRelationType.value = 'blacklist'
      addDialogVisible.value = true
    }

    // 移至黑名单
    const handleMoveToBlacklist = async (relation) => {
      try {
        await ElMessageBox.confirm(
          `确定要将 "${relation.target.nickname}" 移至黑名单吗？`,
          '移至黑名单',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        // 先删除好友关系，再添加黑名单关系
        await deleteUserRelation(relation.id)
        await createUserRelation({
          user_id: props.user.id,
          target_user_id: relation.target.id,
          relation_type: 'blacklist'
        })

        ElMessage.success('已移至黑名单')
        fetchRelations()
        emit('updated')
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('操作失败：' + error.message)
        }
      }
    }

    // 移至好友
    const handleMoveToFriends = async (relation) => {
      try {
        await ElMessageBox.confirm(
          `确定要将 "${relation.target.nickname}" 移至好友列表吗？`,
          '移至好友',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'success'
          }
        )

        // 先删除黑名单关系，再添加好友关系
        await deleteUserRelation(relation.id)
        await createUserRelation({
          user_id: props.user.id,
          target_user_id: relation.target.id,
          relation_type: 'friend'
        })

        ElMessage.success('已移至好友列表')
        fetchRelations()
        emit('updated')
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('操作失败：' + error.message)
        }
      }
    }

    // 删除关系
    const handleDeleteRelation = async (relation) => {
      const relationType = activeTab.value === 'friends' ? '好友' : '黑名单'
      
      try {
        await ElMessageBox.confirm(
          `确定要删除与 "${relation.target.nickname}" 的${relationType}关系吗？`,
          '删除关系',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        await deleteUserRelation(relation.id)
        
        ElMessage.success('关系删除成功')
        fetchRelations()
        emit('updated')
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败：' + error.message)
        }
      }
    }

    // 关闭对话框
    const handleClose = () => {
      visible.value = false
    }

    function getFullImageUrl(url) {
      if (!url) return '';
      if (/^https?:\/\//.test(url)) return url;
      if (url.startsWith('/uploads/avatar/')) return imageBaseUrl.value + url;
      return `${imageBaseUrl.value}/uploads/avatar/${url.replace(/^uploads[\/\\]avatar[\/\\]/, '')}`;
    }

    return {
      visible,
      loading,
      activeTab,
      addDialogVisible,
      addRelationType,
      relations,
      fetchRelations,
      formatDate,
      handleTabChange,
      handleAddFriend,
      handleAddBlacklist,
      handleMoveToBlacklist,
      handleMoveToFriends,
      handleDeleteRelation,
      handleClose,
      getFullImageUrl
    }
  }
}
</script>

<style scoped>
.relations-management {
  max-height: 600px;
  overflow-y: auto;
}

.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  padding: 20px;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.stat-card.friends {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-card.blacklist {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

.stat-card.total {
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
  color: var(--text-primary);
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
}

.tab-content {
  min-height: 300px;
}

.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.tab-header span {
  font-weight: 500;
  color: #303133;
}

.relations-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.relation-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  background-color: #fafafa;
  transition: all 0.3s ease;
}

.relation-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.relation-item.blacklist-item {
  border-color: #f56c6c;
  background-color: #fef0f0;
}

.relation-info {
  flex: 1;
}

.relation-name {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 5px;
}

.relation-details {
  display: flex;
  gap: 15px;
  margin-bottom: 5px;
}

.relation-id {
  color: #909399;
  font-size: 12px;
}

.relation-phone {
  color: #606266;
  font-size: 12px;
}

.relation-time {
  color: #909399;
  font-size: 12px;
}

.relation-actions {
  display: flex;
  gap: 10px;
}

:deep(.el-tabs__header) {
  margin-bottom: 0;
}

:deep(.el-tabs__content) {
  padding-top: 20px;
}
</style> 